<?php

namespace app\store\controller\apps\sharing;

use app\store\controller\Controller;
use app\store\model\user\Grade as GradeModel;
use app\store\model\Delivery as DeliveryModel;
use app\store\model\sharing\Goods as GoodsModel;
use app\store\model\sharing\Category as CategoryModel;
use app\store\model\appointment\Type as TypeModel;
use think\Session;
/**
 * 拼团商品管理控制器
 * Class Goods
 * @package app\store\controller\apps\sharing
 */
class Goods extends Controller
{
    /**
     * 商品列表(出售中)
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 获取全部商品列表
        $model = new GoodsModel;
        $list = $model->getList(array_merge(['status' => -1], $this->request->param()));
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        return $this->fetch('index', compact('list', 'catgory'));
    }

    /**
     * 添加商品
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            // 商品分类
            $catgory = CategoryModel::getCacheTree();
            // 配送模板
            $delivery = DeliveryModel::getAll();
            // 会员等级列表
            $gradeList = GradeModel::getUsableList();

            //预约类型
            $typeModel = new TypeModel();
            $typeList = $typeModel->getList();

            return $this->fetch('add', compact('catgory', 'delivery', 'gradeList', 'typeList'));
        }
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'))) {
            $goods_id = $model->goods_id;
            $this->xcxqrcode($goods_id);
            return $this->renderSuccess('添加成功', url('apps.sharing.goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 复制主商城商品
     * @param $goods_id
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function copy_master($goods_id)
    {
        // 商品详情
        $model = \app\store\model\Goods::detail($goods_id);
        if (!$model || $model['is_delete']) {
            return $this->renderError('商品信息不存在');
        }
        if (!$this->request->isAjax()) {
            // 商品分类
            $catgory = CategoryModel::getCacheTree();

// 配送模板
            $delivery = DeliveryModel::getAll();
            // 商品sku数据
            $specData = 'null';
            if ($model['spec_type'] == 20) {
                $specData = json_encode($model->getManySpecData($model['spec_rel'], $model['sku']), JSON_UNESCAPED_SLASHES);
            }

            // 会员等级列表
            $gradeList = GradeModel::getUsableList();
            return $this->fetch('copy_master', compact('model', 'catgory', 'specData', 'gradeList', 'delivery'));
        }
        // 新增拼团商品
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'))) {
            return $this->renderSuccess('添加成功', url('apps.sharing.goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 一键复制
     * @param $goods_id
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function copy($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            // 商品分类
            $catgory = CategoryModel::getCacheTree();

// 配送模板
            $delivery = DeliveryModel::getAll();
            // 商品sku数据
            $specData = 'null';
            if ($model['spec_type'] == 20) {
                $specData = json_encode($model->getManySpecData($model['spec_rel'], $model['sku']), JSON_UNESCAPED_SLASHES);
            }
            // 会员等级列表
            $gradeList = GradeModel::getUsableList();

            //预约类型
            $typeModel = new TypeModel();
            $typeList = $typeModel->getList();
            return $this->fetch('edit', compact('model', 'catgory', 'specData', 'gradeList', 'typeList','delivery'));
        }
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'))) {
            return $this->renderSuccess('添加成功', url('apps.sharing.goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 商品编辑
     * @param $goods_id
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function edit($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if(!$model['xcx_qrcode']){
            $this->xcxqrcode($goods_id);
        }

        if (!$this->request->isAjax()) {
            // 商品分类
            $catgory = CategoryModel::getCacheTree();
            // 配送模板
            $delivery = DeliveryModel::getAll();
            // 商品sku数据
            $specData = 'null';
            if ($model['spec_type'] == 20) {
                $specData = json_encode($model->getManySpecData($model['spec_rel'], $model['sku']), JSON_UNESCAPED_SLASHES);
            }
            log_print($specData);
            // 会员等级列表
            $gradeList = GradeModel::getUsableList();

            //预约类型
            $typeModel = new TypeModel();
            $typeList = $typeModel->getList();
            return $this->fetch('edit', compact('model', 'catgory', 'specData', 'gradeList', 'typeList', 'delivery'));
        }
        // 更新记录
        if ($model->edit($this->postData('goods'))) {
            return $this->renderSuccess('更新成功', url('apps.sharing.goods/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态
     * @param $goods_id
     * @param boolean $state
     * @return array
     */
    public function state($goods_id, $state)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     * @param $goods_id
     * @return array
     */
    public function delete($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setDelete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }


    function xcxqrcode($id)
    {
        //配置APPID、APPSECRET
        $APPID = "wxfc449efa209ab07e";
        $APPSECRET =  "a46a7f1590681d668f9b175b0cfc9923";
//获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";

//缓存access_token
        Session::set('access_token','');
        Session::set('expires_in',0);


        $ACCESS_TOKEN = "";
        if(! Session::get('access_token') || (Session::get('expires_in')) && time() > Session::get('expires_in'))
        {

            $json = $this->httpRequest( $access_token );
            $json = json_decode($json,true);
            // var_dump($json);
            Session::set('access_token',$json['access_token']);
            Session::set('expires_in',time()+7200);
            $ACCESS_TOKEN = $json["access_token"];
        }
        else{

            $ACCESS_TOKEN =  Session::get('access_token');
        }

//构建请求二维码参数
//path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
//width是二维码宽度
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";

        $param = json_encode(array("path"=>"pages/sharing/goods/index?goods_id=$id","width"=> 150));

//POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");

        $model = new GoodsModel();
        $model->where('goods_id',$id)->update(['xcx_qrcode'=>"xcxqrcode/qrcode_goods_".$id.".png"]);

//生成二维码
        file_put_contents("xcxqrcode/qrcode_goods_".$id.".png", $result);
        //$base64_image ="data:image/jpeg;base64,".base64_encode( $result );

//把请求发送到微信服务器换取二维码
    }

    function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

}
